<template>
  <van-field
    v-model="fieldValue"
    :name="params.value"
    :label="params.label"
    :placeholder="params.placeholder || '请选择'"
    is-link
    v-bind="{ ...params.bind }"
    readonly
    @click="!params.refuseEvent && (showPicker = true)"
  />
  <van-popup
    v-model:show="showPicker"
    title=""
    :safe-area-inset-bottom="true"
    :closeable="true"
    teleport="body"
    close-icon-position="top-left"
    position="right"
    :style="{
      height: '95vh',
      width: '90%',
      bottom: 0,
      top: 'auto',
      transform: 'none',
    }"
    @closed="reset"
  >
    <section class="area">
      <div class="header">省市选择</div>
      <van-index-bar class="content" :index-list="Object.keys(list).sort()">
        <template v-for="item in Object.keys(list).sort()" :key="item">
          <van-index-anchor :index="item" />
          <van-cell
            v-for="ele in list[item]"
            :key="ele"
            :title="ele"
            @click="getNext(ele)"
          />
        </template>
      </van-index-bar>
    </section>
  </van-popup>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { areaList } from '@vant/area-data'
import pinyin from 'pinyin'

const showPicker = ref(false)

const value = ref([])
const code = ref([])

const getPinyinInitial = char => {
  // 使用 pinyin 库将字符转换为拼音
  const result = pinyin(char, {
    style: 'normal',
  })
  return result[0][0][0] // 取首字母并转为大写
}

const getNext = data => {
  value.value.push(data)
  if (value.value.length === 1) {
    code.value.push(provinceObject[data])
    list.value = classifyByInitials(
      Object.values(areaList.city_list).filter(
        item =>
          provinceObject[data].slice(0, 2) === cityObject[item].slice(0, 2),
      ),
    )
  } else if (value.value.length === 2) {
    code.value.push(cityObject[data])
    list.value = classifyByInitials(
      Object.values(areaList.county_list).filter(
        item =>
          cityObject[data].slice(0, 4) === countryObject[item].slice(0, 4),
      ),
    )
  } else {
    code.value.push(countryObject[data])
    showPicker.value = false
    fieldValue.value = value.value.join('')
    emits('update:modelValue', code.value)
    let key = `${props.params.value}_text`
    emits('getText', { [key]: fieldValue.value })
  }
}

const classifyByInitials = names => {
  const classification = {}

  names.forEach(name => {
    const initial = getPinyinInitial(name[0]) // 取名字第一个汉字的首字母
    if (!classification[initial]) {
      classification[initial] = []
    }
    classification[initial].push(name)
    classification[initial].sort()
  })

  return classification
}

const reset = () => {
  value.value = []
  code.value = []
  list.value = classifyByInitials(Object.values(areaList.province_list))
}

const list = ref([])
onMounted(() => {
  list.value = classifyByInitials(Object.values(areaList.province_list))
})

// 将key和value置换
const provinceObject = Object.keys(areaList.province_list).reduce(
  (acc, cur) => {
    acc[areaList.province_list[cur]] = cur
    return acc
  },
  {},
)

const cityObject = Object.keys(areaList.city_list).reduce((acc, cur) => {
  acc[areaList.city_list[cur]] = cur
  return acc
}, {})

const countryObject = Object.keys(areaList.county_list).reduce((acc, cur) => {
  acc[areaList.county_list[cur]] = cur
  return acc
}, {})

const props = defineProps(['params', 'modelValue', 'formParams'])

const fieldValue = ref('')

const emits = defineEmits(['update:modelValue', 'validate', 'getText'])
</script>

<style scoped>
.header {
  text-align: center;
  background: #d3484a;
  color: #fff;
  flex-shrink: 0;
  height: 44px;
  line-height: 44px;
  font-weight: bold;
  z-index: 2;
}
.content {
  height: 100%;
  overflow: auto;
}
.area {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
:deep(.van-popup__close-icon) {
  z-index: 3;
}
</style>
